﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using XYTXL.AppCode;
using XYTXL.Data;
using Newtonsoft.Json;
using System.Web.SessionState;
using XYTXL.API;
using System.Threading.Tasks; 

namespace XYTXL.View.Comon
{
    /// <summary>
    /// UploadFiles 的摘要说明
    /// </summary>
    public class UploadFiles : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            string strAction = context.Request.Form["Action"] ?? "";

            if (strAction == "TX")
            {
                string strUserName = CommonHelp.SessionHelper.GetSession("UserName").ToString();
                UploadTX(context, strUserName);
            }
            else
            {
                context.Response.Write(UploadFile(context));
            }

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }


        public void UploadTX(HttpContext context, string strUserName)
        {
            try
            {
                Result result = new Result();
                result.avatarUrls = new ArrayList();
                result.success = false;
                result.msg = "Failure!";

                string tx_path = FileHelper.GetUploadPath() + "\\TX";

                //取服务器时间+8位随机码作为部分文件名，确保文件名无重复。
                string fileName = DateTime.Now.ToString("yyyyMMddhhmmssff") + CreateRandomCode(8);
                //定义一个变量用以储存当前头像的序号
                int avatarNumber = 1;
                //遍历所有文件域
                foreach (string fieldName in context.Request.Files.AllKeys)
                {
                    HttpPostedFile file = context.Request.Files[fieldName];
                    //处理原始图片（默认的 file 域的名称是__source，可在插件配置参数中自定义。参数名：src_field_name）
                    //如果在插件中定义可以上传原始图片的话，可在此处理，否则可以忽略。
                    if (fieldName == "__source")
                    {
                        //文件名，如果是本地或网络图片为原始文件名（不含扩展名）、如果是摄像头拍照则为 *FromWebcam
                        //fileName = file.FileName;
                        //当前头像基于原图的初始化参数（即只有上传原图时才会发送该数据），用于修改头像时保证界面的视图跟保存头像时一致，提升用户体验度。
                        //修改头像时设置默认加载的原图url为当前原图url+该参数即可，可直接附加到原图url中储存，不影响图片呈现。
                        string initParams = context.Request.Form["__initParams"];
                        result.sourceUrl = string.Format("upload/csharp_source_{0}.jpg", fileName);
                        file.SaveAs(string.Format("{0}\\{1}", tx_path, strUserName + ".jpg"));

                        result.sourceUrl += initParams;
                        /*
                            可在此将 result.sourceUrl 储存到数据库，如果有需要的话。
                        */
                    }
                    //处理头像图片(默认的 file 域的名称：__avatar1,2,3...，可在插件配置参数中自定义，参数名：avatar_field_names)
                    else if (fieldName.StartsWith("__avatar1"))
                    {
                        string virtualPath = string.Format("upload/csharp_avatar{0}_{1}.jpg", avatarNumber, fileName);
                        result.avatarUrls.Add(virtualPath);
                        file.SaveAs(string.Format("{0}\\{1}", tx_path, strUserName + ".jpg"));
                        /*
                            可在此将 virtualPath 储存到数据库，如果有需要的话。
                        */
                        avatarNumber++;
                    }
                    /*
                    else
                    {
                        如下代码在上传接口Upload.aspx中定义了一个user=xxx的参数：
                        var swf = new fullAvatarEditor('swf', {
                            id: 'swf',
                            upload_url: 'Upload.aspx?user=xxx'
                        });
                        在此即可用Request.Form["user"]获取xxx。
                    }
                    */
                }
                result.success = true;
                result.msg = "Success!";
                //返回图片的保存结果（返回内容为json字符串，可自行构造，该处使用Newtonsoft.Json构造）
                context.Response.Write(JsonConvert.SerializeObject(result));

            }
            catch (Exception ex)
            {
                context.Response.Write(ex.Message.ToString() + ex.StackTrace);
            }

        }

        public string UploadFile(HttpContext context)
        {
            context.Response.CacheControl = "no-cache";
            string s_rpath = FileHelper.GetUploadPath();
            //@"E:\My Documents\Visual Studio 2008\WebSites\SWFUpload\demos\applicationdemo.net";

            string strTypeID = context.Request.QueryString["TypeID"] ?? "0";
            string strUserName = context.Request.QueryString["UserName"] ?? "";

            try
            {
                //context.Request.PhysicalApplicationPath +
                string strUploadPath = context.Request.PhysicalApplicationPath + "/View/Upload/" + DateTime.Now.ToString("yyyy-MM-dd");
                if (!Directory.Exists(strUploadPath))
                {
                    Directory.CreateDirectory(strUploadPath);
                }
                if (context.Request.Files.Count > 0)
                {

                    HttpPostedFile uploadFile = context.Request.Files[0];
                    JH_Auth_FormAttchg File = new JH_Auth_FormAttchg();

                    if (uploadFile.ContentLength > 0)
                    {
                        string extname = Path.GetExtension(uploadFile.FileName);

                        File.FileNewName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + uploadFile.FileName.Substring(uploadFile.FileName.LastIndexOf("."));
                        File.FileOldName = uploadFile.FileName;
                        File.FileSize = uploadFile.ContentLength.ToString();
                        File.CRDate = DateTime.Now;
                        File.CRUser = strUserName;
                        File.ProcessID = strTypeID;
                        File.FileType = GetFileType(extname);
                        File.FileUrl = "View/Upload/" + DateTime.Now.ToString("yyyy-MM-dd") + "/" + File.FileNewName;
                        new JH_Auth_FormAttchgB().Insert(File);
                        string fileFullName = string.Format("{0}\\{1}", strUploadPath, File.FileNewName);
                        uploadFile.SaveAs(fileFullName);
                        if (File.FileType == "pic")
                        {
                            ImageCLass.GenSmallImg(fileFullName, 148, 148);
                        }
                        Commanage com=new Commanage();
                        if (extname == ".doc" || extname == ".docx" || extname == ".pdf" || extname == ".pptx")
                        {
                            Task<string> TaskCover = Task.Factory.StartNew<string>(() =>
                            {
                                Msg_Result msg=new Msg_Result();
                                JH_Auth_UserB.UserInfo user=new JH_Auth_UserB.UserInfo();
                                com.IMAGECONVERTER(context, msg, fileFullName, "", user);
                                return "";
                            });
                        }
                    }
                    return JsonConvert.SerializeObject(File);
                }
            }
            catch (Exception ex)
            {
                context.Response.Write("Message" + ex);

            }
            return string.Empty;
        }

        private string GetFileType(string extname)
        {
            switch (extname.ToLower())
            {
                case ".gif":
                case ".jpg":
                case ".bmp":
                case ".jpeg":
                case ".tiff":
                case ".png":
                    return "pic";
                default:
                    return extname.ToLower().TrimStart('.');
            }
        }


        /// <summary>
        /// 生成指定长度的随机码。
        /// </summary>
        private string CreateRandomCode(int length)
        {
            string[] codes = new string[36] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
            StringBuilder randomCode = new StringBuilder();
            Random rand = new Random();
            for (int i = 0; i < length; i++)
            {
                randomCode.Append(codes[rand.Next(codes.Length)]);
            }
            return randomCode.ToString();
        }
        /// <summary>
        /// 表示图片的上传结果。
        /// </summary>
        private struct Result
        {
            /// <summary>
            /// 表示图片是否已上传成功。
            /// </summary>
            public bool success;
            /// <summary>
            /// 自定义的附加消息。
            /// </summary>
            public string msg;
            /// <summary>
            /// 表示原始图片的保存地址。
            /// </summary>
            public string sourceUrl;
            /// <summary>
            /// 表示所有头像图片的保存地址，该变量为一个数组。
            /// </summary>
            public ArrayList avatarUrls;
        }
    }

    /// <summary>
    ///FileHelper 的摘要说明
    /// </summary>
    public class FileHelper
    {
        public FileHelper()
        {
            //
            //TODO: 在此处添加构造函数逻辑
            //
        }
        public static string GetUploadPath()
        {
            string path = HttpContext.Current.Server.MapPath("~/");
            string uploadDir = path + "\\Upload";
            CreateDir(uploadDir);
            return uploadDir;
        }


        private static string GetDirName()
        {
            return System.Configuration.ConfigurationManager.AppSettings["uploaddir"];
        }
        public static void CreateDir(string path)
        {
            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);
            }
        }
    }

}